package top.igotcha.article.controller;

import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.igotcha.article.pojo.Article;
import top.igotcha.article.service.ArticleService;
import top.igotcha.entity.PageResult;
import top.igotcha.entity.Result;
import top.igotcha.entity.StatusCode;

import java.util.List;
import java.util.Map;

/**
 * @author Gotcha
 * @date 2021/1/28
 * @describe
 */
@RestController
@RequestMapping("/article")
@CrossOrigin
public class ArticleController {

    @Autowired
    private ArticleService articleService;
    //查询所有
    @RequestMapping(method = RequestMethod.GET)
    public Result findAll() {
        List<Article> list = articleService.findAll();
        return new Result(true, StatusCode.OK, "查询成功", list);
    }
    //根据id查询
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable("id") String id) {
        Article article = articleService.findById(id);
        return new Result(true, StatusCode.OK, "查询成功", article);
    }

    //新增文章数据接口
    @RequestMapping(method = RequestMethod.POST)
    public Result add(@RequestBody Article article) {
        articleService.add(article);
        return new Result(true, StatusCode.OK, "添加成功");
    }

    //修改文章数据接口
    @RequestMapping(value = "{id}", method = RequestMethod.PUT)
    public Result update(@PathVariable("id") String id, @RequestBody Article article) {
        article.setId(id);
        articleService.update(article);
        return new Result(true, StatusCode.OK, "修改成功");
    }

    //删除文章数据接口
    @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable("id") String id) {
        articleService.delete(id);
        return new Result(true, StatusCode.OK, "删除成功");
    }

    //按条件分页查询
    //接收文章数据如果这里使用pojo，导致所有条件都需要进行判断，遍历pojo需要反射，性能较低，因此直接使用集合进行遍历
    @RequestMapping(value="/search/{page}/{size}", method = RequestMethod.POST)
    public Result search(@RequestBody Map<String,Object> map, @PathVariable("page") int page, @PathVariable("size") int size) {
        //按条件分页查询
        Page<Article> page1 = articleService.search(map, page, size);
        return new Result(true, StatusCode.OK, "查询成功", new PageResult<Article>( page1.getTotal(), page1.getRecords()));
    }

    //统一异常处理测试
    @RequestMapping(value="/exception", method = RequestMethod.GET)
    public Result exception() throws Exception {
        throw new Exception("测试统一异常处理");
    }
}